package me.zhengjie.modules.bushutongji.service.impl;

import me.zhengjie.modules.bushutongji.domain.Goods;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.bushutongji.repository.GoodsRepository;
import me.zhengjie.modules.bushutongji.service.GoodsService;
import me.zhengjie.modules.bushutongji.service.dto.GoodsDTO;
import me.zhengjie.modules.bushutongji.service.dto.GoodsQueryCriteria;
import me.zhengjie.modules.bushutongji.service.mapper.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

/**
* @author xiexidong 
* @date 2019-08-01
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Object queryAll(GoodsQueryCriteria criteria, Pageable pageable){
        Page<Goods> page = goodsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(goodsMapper::toDto));
    }

    @Override
    public Object queryAll(GoodsQueryCriteria criteria){
        return goodsMapper.toDto(goodsRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public GoodsDTO findById(Integer id) {
        Optional<Goods> goods = goodsRepository.findById(id);
        ValidationUtil.isNull(goods,"Goods","id",id);
        return goodsMapper.toDto(goods.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public GoodsDTO create(Goods resources) {
        return goodsMapper.toDto(goodsRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Goods resources) {
        Optional<Goods> optionalGoods = goodsRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalGoods,"Goods","id",resources.getId());
        Goods goods = optionalGoods.get();
        goods.copy(resources);
        goodsRepository.save(goods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        goodsRepository.deleteById(id);
    }

    @Override
    public List<Goods> findGoodsById(int id) {
        return goodsRepository.findGoodsById(id);
    }
}